<template>
    <el-card shadow="always">
     <!-- <h1>{{username}}</h1>
      <h1>{{isadmin}}</h1>     这里对应...mapState(['username','isadmin'])  可以取到值-->
      <!-- 搜索区-->
      <el-form :model="queryParams" ref="queryForm"  :inline="true">
        <el-form-item label="输入用户名" prop="roleName">
          <el-input
              v-model="queryParams.username"
              placeholder="请输入用户名"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="load"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="load">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="reset" >重置</el-button>
        </el-form-item>
      </el-form>

      <!--按钮区域    -->
      <el-row :gutter="10" class="mb8" style="margin:5px">
        <el-button type="primary" size="mini" @click="add()">新增</el-button>
      </el-row>

      <!-- 列表区-->
      <el-table :data="tableData" :header-cell-style="{background:'#F8F8F9'}"  style="width: 100%">
       <!-- <el-table-column type="selection" width="55" align="center" />--> <!--  加了这个表格的每一行会有复选框 -->
        <el-table-column type="index"  :index="indexMethod" label="编号" width="100px"></el-table-column>
        <!--<el-table-column prop="id"  label="ID"></el-table-column>-->
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="nickName" label="昵称"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="age" sortable label="年龄"></el-table-column>
        <el-table-column prop="roleName" label="角色"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column fixed="right" label="操作" width="260">
          <template #default="scope">
            <button type="button" @click="handleEdit(scope.row)"  class="el-button el-button--text el-button--mini"><!----><i class="el-icon-edit"></i><span>修改</span></button>
            <button type="button"  @click="handleDelete(scope.row)" class="el-button el-button--text el-button--mini"><!----><i class="el-icon-delete"></i><span style="color:red">删除</span></button>
            <button type="button" v-show="isadmin"  @click="resetPassword(scope.row)" class="el-button el-button--text el-button--mini"><!----><i class="el-icon-key"></i><span>重置密码</span></button>
          </template>
        </el-table-column>
      </el-table>
      <!--列表分页-->
      <div style="margin: 10px 0">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"> //双引号里面的total是定义一个变量，在这里定义了，就需要在下面data里面初始化一下
        </el-pagination>

        <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :append-to-body="true" >
          <el-form :model="user" label-width="120px">
            <el-form-item label="姓名:">
              <el-input v-model="user.username" style="width:80%"></el-input>
            </el-form-item>
            <el-form-item label="用户头像:">
              <el-upload
                  class="avatar-uploader"
                  action="/api/sys/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">

                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="昵称:">
              <el-input v-model="user.nickName" style="width:80%"></el-input>
            </el-form-item>

            <el-form-item label="年龄:">
              <el-input v-model="user.age" style="width:80%"></el-input>
            </el-form-item>

            <el-form-item label="性别:">
              <el-radio v-model="user.sex" label="男">男</el-radio>
              <el-radio v-model="user.sex" label="女">女</el-radio>
            </el-form-item>

            <el-form-item label="角色:">
              <el-radio-group v-model="user.roleId"  >
                <el-radio v-for="(item,index) in roles" :key="index"  :label="item.roleId">{{item.roleName}}</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="地址:">
              <el-input type="textarea" v-model="user.address" style="width:80%"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
          <span class="dialog-footer">
            <el-button size="small" @click="dialogVisible = false">取 消</el-button>
            <el-button size="small" type="primary" @click="save">确 定</el-button>
          </span>
          </template>
        </el-dialog>
      </div>
    </el-card>
</template>

<script>
import request from "../utils/request";
import {mapState} from "vuex";

export default {
  name: 'user',
  components: {},
  data() {
    return {
      title: '',
      user: {url:""},
      dialogVisible: false,
      // 查询参数
      queryParams: {
        username: undefined,
      },
      currentPage: 1,
      pageSize: 5,
      total: 0,  //默认10条
      tableData: [],
      imageUrl: '',

      // 角色选项
      roles: [],

    }
  },

  //页面加载完立即执行的方法
  created() {
    this.load()
  },


  computed: {
    ...mapState(['username','isadmin']),

    uploadDisabled:function() {
      return this.fileList.length >0
    },

  },
  methods: {

    indexMethod(index) {
      return index+1 ;
    },


    //查询方法
    load() {
      request.get("/user/selectList", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          nickName: this.queryParams.nickName,
          username: this.queryParams.username
        }
      }).then(res => {
        this.tableData = res.data.list
        this.total = res.data.total
      }).catch(error=>error)

    },

    //新增打开弹窗方法
    add() {
      this.dialogVisible = true;
      this.title = "新增"
      this.user = {}; //清空表单中的值
      request.get("/user/info").then(res => {
        this.roles=res.data.roles;
      }).catch(err =>err);

    },

    //进行保存 使用aios进行数据交互
    save() {
      if (this.user.id) {   //如果有id,则进行更新操作  并且更新使用put请求
        request.put("/user/update", this.user).then(res => {
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "修改成功"
            })
          } else {
            this.$message({
              type: "error",
              message: "修改失败"
            })
          }
          this.load();  //更新完成后，重新刷新表格数据
          this.dialogVisible = false;    //最后关闭弹窗

        })
      } else {     //如果没有id,则进行新增操作
        request.post("/user/save", this.user).then(res => {
          this.$message({
            type: "success",
            message: res.msg
          })
          this.load();  //更新完成后，重新刷新表格数据
          this.dialogVisible = false;    //最后关闭弹窗
        })
      }


    },

    //编辑打开弹窗方法
    handleEdit(row) {
      this.user = JSON.parse(JSON.stringify(row));  //将编辑的弹窗附上值
      request.get("/user/info").then(res => {
        this.roles=res.data.roles;
      }).catch(err =>err);
      this.dialogVisible = true;  //打开编辑的弹窗（和新增用的一个弹窗）
      this.title = "编辑"
    },


    //删除方法
    handleDelete(row) {
        this.$confirm('确定要删除该用户吗?, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          request.delete("/user/del/" + row.id).then(res => {
            if (res.code === '0') {
              this.$message({
                type: "success",
                message: "删除成功"
              })
            } else {
              this.$message({
                type: "error",
                message: res.msg
              })
            }
            this.load()
          })
        })
    },


    //重置密码
    resetPassword(row){
        this.$confirm('确定要重置密码吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            request.get("/user/resetPassword/" + row.id).then(res => {
                if (res.code === '0') {
                    this.$message({
                        type: "success",
                        message: res.msg
                    })
                } else {
                    this.$message({
                        type: "error",
                        message: res.msg
                    })
                }
                this.load()
            })
        })
    },


    /** 重置按钮操作 */
    reset() {
      this.queryParams = {};
    },

    //在上面的data中，pageSize和currentPaage都有默认值，这里要触发分页，需要重新根据变量赋值
    //改变当前每页条数触发
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },

    //改变当前页码触发
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum
      this.load()
    },



    //上传成功
    handleAvatarSuccess(res, file) {
      debugger
      //this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = "/api"+res.data;
    },


    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },



  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
}

.el-icon-delete{
  color:red
}

 .el-dialog__header {
  border-bottom: 1px solid #ebebeb;
}







</style>
